//
//  CXADViewController.m
//  喜马拉雅FM
//
//  Created by hcios on 2017/8/29.
//  Copyright © 2017年 hcios. All rights reserved.
//

#import "CXADViewController.h"
#import "CXADItem.h"
#import "CXTabBarViewController.h"
#import "CXTabBarConfig.h"
#define kApiKey @"phcqnauGuHYkFMRquANhmgN_IauBThfqmgKsUARhIWdGULPxnz3vndtkQW08nau_I1Y1P1Rhmhwz5Hb8nBuL5HDknWRhTA_qmvqVQhGGUhI_py4MQhF1TvChmgKY5H6hmyPW5RFRHzuET1dGULnhuAN85HchUy7s5HDhIywGujY3P1n3mWb1PvDLnvF-Pyf4mHR4nyRvmWPBmhwBPjcLPyfsPHT3uWm4FMPLpHYkFh7sTA-b5yRzPj6sPvRdFhPdTWYsFMKzuykEmyfqnauGuAu95Rnsnbfknbm1QHnkwW6VPjujnBdKfWD1QHnsnbRsnHwKfYwAwiu9mLfqHbD_H70hTv6qnHn1PauVmynqnjclnj0lnj0lnj0lnj0lnj0hThYqniuVujYkFhkC5HRvnB3dFh7spyfqnW0srj64nBu9TjYsFMub5HDhTZFEujdzTLK_mgPCFMP85Rnsnbfknbm1QHnkwW6VPjujnBdKfWD1QHnsnbRsnHwKfYwAwiuBnHfdnjD4rjnvPWYkFh7sTZu-TWY1QW68nBuWUHYdnHchIAYqPHDzFhqsmyPGIZbqniuYThuYTjd1uAVxnz3vnzu9IjYzFh6qP1RsFMws5y-fpAq8uHT_nBuYmycqnau1IjYkPjRsnHb3n1mvnHDkQWD4niuVmybqniu1uy3qwD-HQDFKHakHHNn_HR7fQ7uDQ7PcHzkHiR3_RYqNQD7jfzkPiRn_wdKHQDP5HikPfRb_fNc_NbwPQDdRHzkDiNchTvwW5HnvPj0zQWndnHRvnBsdPWb4ri3kPW0kPHmhmLnqPH6LP1ndm1-WPyDvnHKBrAw9nju9PHIhmH9WmH6zrjRhTv7_5iu85HDhTvd15HDhTLTqP1RsFh4ETjYYPW0sPzuVuyYqn1mYnjc8nWbvrjTdQjRvrHb4QWDvnjDdPBuk5yRzPj6sPvRdgvPsTBu_my4bTvP9TARqnam"

@interface CXADViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *launchImageView;

@property (weak, nonatomic) IBOutlet UIView *addContainView;

@property (nonatomic, weak) UIImageView *adImageView;   //广告图片view

@property (nonatomic, strong) CXADItem *item;

@property (nonatomic, weak) NSTimer *timer;

@property (weak, nonatomic) IBOutlet UIButton *jumpBtn;

@end

@implementation CXADViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置启动图片
    [self setupLaunchImageView];
    
    //加载广告数据
    [self loadADData];
    
    //创建定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerChanged) userInfo:nil repeats:YES];
}


#pragma mark - 定时器方法
- (void)timerChanged {
    
    // 倒计时
    static int i = 3;
    if (i == 0) {
        [self didClickJumpButton:nil];
    }
    i--;
    
    // 设置跳转按钮文字
    [_jumpBtn setTitle:[NSString stringWithFormat:@"  跳过（%d）", i] forState:UIControlStateNormal];
}

#pragma mark - 加载广告数据
- (void)loadADData {
    
    // 1、创建请求会话管理者
    AFHTTPSessionManager * mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    
    // 2. 拼接参数
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"code2"] = kApiKey;
    
    // 3、发送请求
    [mgr GET:@"http://mobads.baidu.com/cpro/ui/mads.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        NSLog(@"网络请求成功");
        
        NSDictionary * responseObjcDict = responseObject;
        NSDictionary * adDict = [responseObjcDict[@"ad"] lastObject];
        
        // 字典转模型
        _item = [CXADItem mj_objectWithKeyValues:adDict];
        
        // 创建UIimageView展示图片
        CGFloat h = DEVICE_SCREEN_WIDTH / _item.w * _item.h ? _item != nil : _item == nil;
        self.adImageView.frame = CGRectMake(0, 0, DEVICE_SCREEN_WIDTH, h);
        // 加载广告图片
        [self.adImageView sd_setImageWithURL:[NSURL URLWithString:_item.w_picurl]];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        NSLog(@"网络请求失败");
    }];
}


#pragma mark - 加载启动图片
- (void)setupLaunchImageView {
    
    if (UI_IS_IPHONE6PLUS) {
        self.launchImageView.image = kGetImage(@"LaunchImage-800-Portrait-736h@3x");
    } else if (UI_IS_IPHONE6) {
        self.launchImageView.image = kGetImage(@"LaunchImage-800-667h");
    } else if (UI_IS_IPHONE5) {
        self.launchImageView.image = kGetImage(@"LaunchImage-568h");
    } else if (UI_IS_IPHONE4 ) {
        self.launchImageView.image = kGetImage(@"LaunchImage-700");
    }
}

#pragma mark - lazy load method
- (UIImageView *)adImageView {
    
    if (!_adImageView) {
        UIImageView * adImageView = [[UIImageView alloc] init];
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didClickAdImageView)];
        [adImageView addGestureRecognizer:tap];
        adImageView.userInteractionEnabled = YES;
        
        [self.addContainView addSubview:adImageView];
        _adImageView = adImageView;
    }
    return _adImageView;
}

#pragma mark - action
#pragma mark - 点击广告view
- (void)didClickAdImageView {
    
    // 跳转界面 => safari
    NSURL * url = [NSURL URLWithString:_item.ori_curl];
    UIApplication * app = [UIApplication sharedApplication];
    
    if ([app canOpenURL:url]) {
        [app openURL:url];
    }
}
- (IBAction)didClickJumpButton:(UIButton *)btn {
    
    //销毁广告页面，进入主框架界面
    CXTabBarViewController *tabBarVC = [CXTabBarConfig cx_configTabBarController];
    [UIApplication sharedApplication].keyWindow.rootViewController = tabBarVC;
    
    //定时器的销毁
    [self.timer invalidate];
}

@end
